package com.qidian.buy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.entity.Customer;
import com.qidian.buy.mapper.CustomerMapper;
import com.qidian.buy.service.ICustomerService;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.LayuiTableDTO;
import com.qidian.buy.util.pojo.QDResult;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author 郭浩
 */
@Service
public class CustomerServiceImpl implements ICustomerService {
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public QDResult save(Customer customer) {
        if (customerMapper.insert(customer)==1){
            return QDResult.ok();
        }
        return QDResult.fal();
    }

    @Override
    public QDResult edit(Customer customer) {
        if (customerMapper.updateById(customer)==1){
            return QDResult.ok();
        }
        return QDResult.fal();
    }

    @Override
    public QDResult delete(Customer customer) {
        if (customerMapper.updateById(customer)==1){
            return QDResult.ok();
        }
        return QDResult.fal();
    }

    @Override
    public QDResult<Customer> get(Long id) {
        Customer customer = customerMapper.selectById(id);
        if (customer!=null){
            QDResult.ok(customer);
        }
        return QDResult.notFound();
    }

    @Override
    public LayuiTableDTO<Customer> query(int page, int limit, Customer customer) {
        LayuiTableDTO<Customer> dto = new LayuiTableDTO<>();
        Page<Customer> pager = new Page<>();
        pager.setCurrent(page);
        pager.setSize(limit);
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        // 组织查询条件
        if(customer != null) {
            wrapper.like(customer.getNickname()!=null && !customer.getNickname().equals(""),"nickname", customer.getNickname());
            wrapper.eq(customer.getUserGender()!=null && customer.getUserGender().equals(0),"user_gender",customer.getUserGender());
            wrapper.eq(customer.getStatus()!=null && customer.getStatus().equals(0),"status",customer.getStatus());
        }
        pager = customerMapper.selectPage(pager,wrapper);
        dto.setCount(pager.getTotal());
        dto.setData(pager.getRecords());
        return dto;

    }


    public QDResult reg(Customer customer){
        // 补全数据
        customer.setCreated(new Date());
        customer.setUpdated(new Date());
        customer.setStatus(1);
        customer.setUsername("用户"+getCode()+getCode());
        // 密码要加密,这里使用MD5  我们这里使用Spring提供的一个工具类进行加密
        String s = DigestUtils.md5DigestAsHex(customer.getPassword().getBytes());
        customer.setPassword(s);// 将密码修改为加密后的密码
        return customerMapper.insert(customer)==1?QDResult.ok(customer):QDResult.fal();
    }

    @Override
    public QDResult login(String loginName, String password) {
        // 查询用户
        Customer c = null;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", loginName);
        c = customerMapper.selectOne(wrapper);
        if (c == null) {
            wrapper = new QueryWrapper();
            wrapper.eq("user_tel", loginName);
            c = customerMapper.selectOne(wrapper);
        }
        if (c == null) {
            return QDResult.fal();
        }
        // 比对密码
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (password.equals(c.getPassword())) {
            // 将用户信息放入redis
            // 删除用户的密码
            c.setPassword("");
            // 转为JSON
            String json = JSONTools.object2json(c);
            // 生成token
            String token = UUID.randomUUID().toString().replace("-", "_");
            stringRedisTemplate.opsForValue().set(token, json);
            // 将客户信息和token放在result中响应到客户端去
            return QDResult.ok(token, c);
        }
        return QDResult.fal();
    }
    public QDResult getCustomerByToken(String token){
        if(stringRedisTemplate.hasKey(token)) {
            String customerJson = stringRedisTemplate.opsForValue().get(token);
            try{
                Customer c = JSONTools.json2object(customerJson,Customer.class);
                QDResult result  = QDResult.ok(c);
                // 刷新redis中用户登陆信息的时间
                stringRedisTemplate.expire(token,30, TimeUnit.MINUTES);
                return result;
            }catch (Exception e){
                // 记录异常
            }
        }
        return QDResult.fal();
    };

    private String getCode(){
        return  (new Random().nextInt(9000)+1000)+"";
    }
}

